package com.example.treeHole.service.impl;

import com.example.treeHole.dao.*;
import com.example.treeHole.exception.CustomException;
import com.example.treeHole.service.ArticleMainService;
import com.example.treeHole.service.SensitiveWordService;
import com.example.treeHole.utils.BaseContext;
import com.example.treeHole.utils.Uuid;
import com.example.treeHole.vo.ArticleMain;
import com.example.treeHole.vo.ArticleReply;
import com.example.treeHole.vo.NotificationMain;
import com.example.treeHole.vo.VirtualCharacter;
import com.example.treeHole.vo.dto.ArticleMainDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleMainServiceImpl implements ArticleMainService {

    @Autowired
    private SensitiveWordService sensitiveWordService;

    @Autowired
    private ArticleMainMapper articleMainMapper;

    @Autowired
    private ArticleReplyMapper articleReplyMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VirtualCharacterMapper virtualCharacterMapper;

    @Autowired
    private ArticleLikeMapper articleLikeMapper;

    @Autowired
    private CollectMainMapper collectMainMapper;

    @Autowired
    private NotificationMainMapper notificationMainMapper;

    /**
     * 分页查询文章
     *
     * @param articleMainDto
     * @return
     */
    @Override
    public PageInfo<ArticleMain> findPage(ArticleMainDto articleMainDto) {
        PageHelper.startPage(articleMainDto.getPageNum(), articleMainDto.getPageSize());
        //先查出来所需的文章
        List<ArticleMain> articleMainList = articleMainMapper.findPage(articleMainDto);
        //取出所有文章ID
        List<String> articleIds = articleMainList.stream()
                .map(ArticleMain::getArticleId)
                .collect(Collectors.toList());
        if(articleIds.size()==0){
            return PageInfo.of(new ArrayList<>());
        }else {
            //通过文章id查询，把对应的评论数量查出来，使用map接收只需要对应的文章id和评论数量
            List<Map<String, Object>> ACount = articleReplyMapper.findArticleReplyCount(articleIds);
            //通过文章ids查询，把对应的是点赞实现，使用map接收只需要对应的文章id和是否收藏本文章。
            List<Map<String, Object>> replyCMap = articleReplyMapper.findARCountByList(articleIds, BaseContext.getCurrentId());
            //通过文章ids查询，把对应的是否收藏实现，使用map接收只需要对应的文章id和是否收藏本文章。
            List<Map<String, Object>> collectMap = collectMainMapper.findCSByList(articleIds, BaseContext.getCurrentId());
            Map<String, Map<String, Object>> articleCount = delListMap(ACount, "articleId");
            Map<String, Map<String, Object>> likeMap = delListMap(replyCMap, "articleId");
            Map<String, Map<String, Object>> collectMap1 = delListMap(collectMap, "articleId");
            for (ArticleMain articleMain : articleMainList) {
                String articleId = articleMain.getArticleId();
                Map<String, Object> stringStringMap = likeMap.get(articleId);
                Map<String, Object> collectStatus = collectMap1.get(articleId);
                Map<String, Object> aCount = articleCount.get(articleId);
                if (stringStringMap != null) {
                    Long likeCount = (Long) stringStringMap.get("likeCount");
                    articleMain.setLikeCount(likeCount.intValue());
                    Long likeStatus = (Long) stringStringMap.get("likeStatus");
                    if (likeStatus == 1) {
                        articleMain.setLikeStatus(true);
                    }
                }
                if (collectStatus != null) {
                    Long collectStatus1 = (Long) collectStatus.get("collectStatus");
                    if (collectStatus1 == 1) {
                        articleMain.setCollectStatus(true);
                    }
                }
                if (aCount != null) {
                    Long articleCount1 = (Long) aCount.get("articleCount");
                    articleMain.setArticleCount(articleCount1.intValue());
                }
            }
            return PageInfo.of(articleMainList);
        }
    }

    /**
     * 处理集合，
     * @param listMap
     * @param key
     * @return
     */
    public Map<String,Map<String,Object>> delListMap(List<Map<String,Object>> listMap,String key){
        Map<String,Map<String,Object>> likeMap=new HashMap<>();
        for (Map<String, Object> stringStringMap : listMap) {
            String id = (String)stringStringMap.get(key);
            likeMap.put(id,stringStringMap);
        }
        return likeMap;
    }

    @Override
    public String create(ArticleMain articleMain) {
        articleMain.setArticleId(Uuid.getUuID());
        articleMain.setCreateDate(new Date());
        articleMain.setCreateBy(BaseContext.getCurrentId());
        //进行敏感词过滤操作
        String s = sensitiveWordService.filterText(articleMain.getArticleContent());
        if("请等待管理员审批".equals(s)){
            articleMain.setStatus("0");
            articleMainMapper.insert(articleMain);
            //todo 消息通知
            NotificationMain notificationMain =new NotificationMain();
            notificationMain.setId(Uuid.getUuID());
            notificationMain.setNotificationStatus("0");
            notificationMain.setNotificationCategory("6");
            notificationMain.setAcceptId("1");
            notificationMain.setSendId(BaseContext.getCurrentId());
            notificationMain.setNotificationType("1");
            notificationMain.setArticleId(articleMain.getArticleId());
            notificationMain.setCreateDate(new Date());
            notificationMainMapper.insert(notificationMain);
            return "文章包含敏感词，请等待管理员审核";
        }else {
            articleMain.setStatus("1");
            articleMainMapper.insert(articleMain);
            return "文章已发布";
        }
    }

    /**
     * 根据id查询文章
     *
     * @param articleId
     * @return
     */
    @Override
    public ArticleMain findById(String articleId) {
        if (StringUtils.isEmpty(articleId)) {
            throw new CustomException("传参异常");
        }
        //现根据id把文章查询出来并且把对应的虚拟人物查出来
        ArticleMain articleMain = articleMainMapper.selectAMById(articleId);
        //根据文章Id把文章回复查出来  is_reply 1:回复文章 2:表示回复文章的回复
        List<ArticleReply> articleReply = articleReplyMapper.findReplyByAId(articleId);
        Collections.sort(articleReply, new Comparator<ArticleReply>() {
            @Override
            public int compare(ArticleReply o1, ArticleReply o2) {
                return o1.getCreateDate().compareTo(o2.getCreateDate());
            }
        });
        //for循环处理
        for (ArticleReply reply : articleReply) {
            if ( "1".equals(reply.getIsReply())){
                for (ArticleReply articleReply1 : articleReply) {
                    if( ("2".equals(articleReply1.getIsReply()) && articleReply1.getReplyId() .equals(reply.getId())
                            || ( "3".equals(articleReply1.getIsReply()) && articleReply1.getReplyId() .equals(reply.getId())))){
                        List<ArticleReply> childReply = reply.getChildReply();
                        if(childReply==null){
                            List<ArticleReply> articleReplies =new ArrayList<>();
                            articleReplies.add(articleReply1);
                            reply.setChildReply(articleReplies);
                        }else {
                            childReply.add(articleReply1);
                            reply.setChildReply(childReply);
                        }}}}}
        List<ArticleReply> collect = articleReply.stream()
                .filter(articleReply1 -> "1".equals(articleReply1.getIsReply())).collect(Collectors.toList());
        if(collect!=null){
            articleMain.setArticleCount(collect.size());
        }
        articleMain.setMainReply(collect);
        return articleMain;
    }}
